var app = window.app = {};
window.localStorage.setItem('in',0);
/**
 * 请求地址集合
 * @type {Object}
 */
app.link = {
//baseUrl: 'http://192.168.1.110',
//uploadUrl: 'http://192.168.1.110',
//imageUrl: 'http://192.168.1.110',
//apiUrl: 'http://192.168.1.110/App',
//baseUrl: 'http://webapi.52ywy.com/',
uploadUrl: 'http://webapi.52ywy.com//Files',
imageUrl: 'http://webapi.52ywy.com/',
apiUrl: '/App'
};

/**
 * 分页配置
 */
app.pagination = {
   page: 1,
   nums: 10
}; 

/**
 * ajax请求
 * @author Robin
 * @date   2016-05-23
 * @param  {Object}   url     请求地址（或json对象）
 * @param  {Object}   data    请求数据
 * @param  {Object}   success 成功回调
 * @param  {Object}   dom     填充对象节点
 * @param  {Object}   tpl     模板
 * @return {Object}           
 */
app.ajax = function (url, data, success, dom, tpl) {
  var hash = {};
  if ('object' === typeof(url)) {
    hash.async    = url.async ? true : false;
    hash.type     = url.type ? url.type : 'POST';
    hash.url      = app.link.apiUrl + url.url;
    hash.dataType = url.dataType ? url.dataType : 'json';
    hash.data     = url.data ? url.data : {};
    hash.timeout  = 3000;
    hash.error = function (res) {
      app.log('error: ', hash.url + ', ' + JSON.stringify(res));
      return url.error && url.error(res);
    };
    hash.beforeSend = function(){
    	/*$('body').append("<div class='tC promp-order' id='promp-order' style='position:absolute;top:30%;left:15%;height:30%;width:70%;'>"
								+"<img src='../img/animate/3.png' class='dIB' id='eat' style='width:60px;position:absolute;left:4rem;'/>"
								+"<img src='../img/animate/6.png' class='dIB' id='food' style='width:16px;position:absolute;top:25px;left:10rem;'/>"
								+"<img src='../img/animate/6.png' class='dIB' id='food2' style='width:16px;position:absolute;top:25px;left:13rem;'/><p class='fS15 tC' style='margin-top:85px' >上洋玩易，吃好吃的！</p></div>");*/
//		app.open('404.html','404html',{},window.location.href,document.body.scrollTop);
    };
    hash.success = function (res) {
		
      app.log('info: ', hash.url + ', ' + JSON.stringify(res));
      if (url.dom && url.tpl) app.tpl(url.dom, url.tpl, res.data);
      return url.success && url.success(res);
    };
  } else {
    hash.type     = 'POST';
    hash.url      = app.link.apiUrl + url;
    hash.dataType = 'json';
    hash.data     = data ? data : {};
    hash.error = function (res) {
//		$('body').css('background','#fff!important');
//		$('body').html("<div class='tC fS12 four' style='position:absolute;top:30%;left:10%;height:30%;width:80%;'><img src='../img/icon/no.png' class='w'/>"
//						+"<div class='oF mT20 '><div class='fl w70'><img src='../img/icon/wenzi.png' class='w70'/></div><div class='fr w30'>"
//						+"<button class='btn btn-red1 pL10 pR10 pT5 pB5 fS13 return-home'>返回首页</button></div></div></div>");
//		header.init('洋玩易');
//		$('body').on('click','.return-home',function(){
//			$('.four').remove();
//			app.open('../html/main.html','main',{},window.location.href,document.body.scrollTop);
//		});
    };
    hash.beforeSend = function(){
//		var id = "body-loading";
//		$(window).loading({action:"open",id:id,font:40});
			//关闭
//		$('body').append("<div class='tC promp-order' id='promp-order' style='position:absolute;top:30%;left:15%;height:30%;width:70%;'>"
//						+"<img class='dIB' id='eat' style='width:60px;position:absolute;left:4rem;'/>"
//						+"<img src='../img/animate/6.png' class='dIB' id='food' style='width:16px;position:absolute;top:25px;left:10rem;'/>"
//						+"<img src='../img/animate/6.png' class='dIB' id='food2' style='width:16px;position:absolute;top:25px;left:13rem;'/><p class='fS15 tC' style='margin-top:85px' >上洋玩易，吃好吃的！</p></div>");
//			ani.init();
//app.open('404.html','404html',{},window.location.href,document.body.scrollTop);

    };
    hash.success = function (res) {
  //  	$('#loading').hide();
//    api.refreshHeaderLoadDone();
//		var id = "body-loading";
//		$(window).loading({action:"close",id:id});
//		ani.cle();
//		$('#promp-order').remove();
//window.close('404.html');


	if (res.code === 301 && window.location.pathname.indexOf('login')== -1) {
			layer.msg(res.msg);	
			setTimeout(function(){
				window.location.href='login.html';
			},2000)
			return;
	}
      app.log('info: ', hash.url + ', ' + JSON.stringify(res));
      if (dom && tpl) app.tpl(dom, tpl, res.data);
      return success && success(res);
    };
  }
  //token用户登录判断
//var token = app.store('token');
//if (token) {
//	hash.data = $.extend({}, { token: token }, hash.data);
//}
//hash.data = $.extend({}, app.pagination, hash.data);
// 

  $.ajax(hash);
}


/**
 * 获取请求参数
 * @param  {Object} name 键名
 * @return {Object}      
 */
//app.getQueryString = function (name){
//if (!name) return undefined;
//var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
//var r = top.window.location.search.substr(1).match(reg);
//if (r!=null) return unescape(r[2]); return undefined;
//}
//
///**
// * 获取请求参数并转成json
// * @param  {Object} url 请求地址
// * @return {Object} 
// */
//app.parseQueryString = function (url) {
//return $.deparam.querystring(url || top.window.location);
//}

/**
 * 添加/获取缓存数据
 * @param {Object} key
 * @param {Object} value
 */
app.store = function (key, value) {
  if (!key && !value) {
    return undefined;
  } else if (key && value) {
    var v = 'string' == typeof(value) ? value : JSON.stringify(value);
    localStorage.setItem(key, v);
  } else if (!value) {
    var v = localStorage.getItem(key);
    if (v && ('{' == v.charAt(0) || '[' == v.charAt(0))) {
      try { v = JSON.parse(v) } catch (e) {}  
    }
    return v;
  }
}

/**
 * 开发时用于打印日志，上线后此方法内不做任何事
 * @param {Object} data
 */
app.log = function (key, value) {
  if (undefined == value) {value = key, key = ''}
  
  if ('string' == typeof(value)) {
   // console.log(key + value);
  } else {
    //console.log(key + JSON.stringify(value));
  }
}

/**
 * 取得ArtTemplate并填充数据再把数据放于直接dom下。已做try catch处理
 * @param {Object} 用于放置构造出来的tpl代码的容器，可是jquery对象也可以是jquery的选择表达式
 * @return {String} 模板ID
 * @return {Object} 数据
 */
app.tpl = function (dom, tpl, data) {
  if (undefined !== data) {
    try { $(dom).html(template(tpl, data)); } catch (e) { app.log(e); };  
  } else if (undefined !== tpl) {
    return template(dom, tpl);
  }
 
};

app.tpladd=function (dom, tpl, data) {
  if (undefined !== data) {
    try { $(dom).append(template(tpl, data)); } catch (e) { app.log(e); };  
  } else if (undefined !== tpl) {
    return template(dom, tpl);
  }
 
};

/**
 * 添加浏览记录
 * @param {Object} value
 */
app.putHis = function (value) {
  var his = app.store('history');
  if (his) {    
    if (his[his.length - 1] === value) return;
    his.push(value);
  } else {
    his = [value];
  }
  app.store('history', his);
}

/**
 * 清空浏览记录
 */
app.clearHis = function () {
  app.store('history', []);
}

/**
 * 获取上一条浏览记录并删除
 * @return {Object} value
 */
app.popHis = function () {
  var his = app.store('history');
  if (!his || !his.length) return undefined;
  if (his.length !== 1) his.pop();
  var value = his.pop();
  app.store('history', his);
  return value;
}

template.helper('moneyFormat', function (money, dec) {
	var money= parseFloat(money);
	console.log(dec);
	console.log(Math.floor(money));
	if( dec == 0){ return Math.floor(money);
	}else{
		return	(money/100).toFixed(dec ? dec : 2);
	}
});

template.helper('datetimeFormat', function (datetime, format) {
  var date = datetime ? new Date(parseInt(datetime) * 1000) : new Date();
  var map = {  
              M: date.getMonth() + 1, //月份   
              d: date.getDate(), //日   
              h: date.getHours(), //小时   
              m: date.getMinutes(), //分   
              s: date.getSeconds(), //秒   
              S: date.getMilliseconds() //毫秒   
            };  
  format = format ? format : 'yy-MM-dd';
  if(format == '年月日'){
	var data1 = datetime.substr(0,10);
	data1 = data1.split('-');
	format = data1[0]+'年'+data1[1]+'月'+data1[2]+'日';
  	return format;
  }
  if(format == 'MM/dd'){
  		var data1 = datetime.substr(0,10);
		data1 = data1.split('-');
		format = data1[1]+'/'+data1[2];
  		return format;
  }
  format = format.replace(/([yMdhmsS])+/g, function(all, t){  
    var v = map[t];  
    if (v !== undefined) {  
      if (all.length > 1) {  
        v = '0' + v;  
        v = v.substr(v.length - 2);  
      }  
      return v;  
    } else if (t === 'y') {  
      return (date.getFullYear() + '').substr(4 - all.length);  
    }  
    return all;  
  });  
  return format;
});

template.helper('thumbImage', function (url, width, height) {
  if (!url) return 'default.png';
  if (!width) return app.link.imageUrl + url;
  if (!height) height = width;

  var idx = url.lastIndexOf('.');
  return app.link.imageUrl + url.substr(0, idx) + '_' + width + '_' + height + url.substr(idx);
});
template.helper('textSubstr', function (text,length) {
  if(!text) return;
  if (!length) length=6;
  if(text.length <=length) return text;
  return text.substr(0, length)+'...';
});

template.helper('phone', function (text) {
  if(!text) return;
  return text.substring(0,3)+'****'+text.substring(8,11);
});

/**
 * 上传图片
 * @param  {Function} cb 回调函数
 */
app.wxUploadImage = function (cb) {
  var ary = [], len = 0;
  wx.chooseImage({
    count: 9, 
    sizeType: ['original', 'compressed'], 
    sourceType: ['album', 'camera'], 
    success: function (res) {
      len = res.localIds.length;
      for (var i = 0; res.localIds[i]; i++) {
        wx.uploadImage({
          localId: res.localIds[i], 
          isShowProgressTips: 1, 
          success: function (res) {
            ary.push(res.serverId);
            if (ary.length == len) { cb && cb(ary); };
          }
        });
      }
    }
  });
}
/**
 * 打开一个完全自己定义的新页面
 * @param {Object} link
 * @param {Object} data
 */
app.open = function (link,sname,data,localLink,localTop) {
	if(data){
		var data=JSON.stringify(data);
		
	 	window.sessionStorage.setItem(''+sname,data);
	 	window.localStorage.setItem(''+sname,data);
 	}
	console.log(localLink);
	if(localLink){
		if(!window.sessionStorage.getItem('historycode')){
		 	var a=localTop+','+localLink+';';
		 	console.log(a);
		 	window.sessionStorage.setItem('historycode',a);
		 }else{
		 	var a=window.sessionStorage.getItem('historycode')+localTop+','+localLink+';';
		 	console.log(a);
		 	window.sessionStorage.setItem('historycode',a);
		 }
	 }
	if(link) window.location.href=link;
};

app.toHistory=function(link){
	var a=window.sessionStorage.getItem('historycode');
	if(a){
		a=a.split(';');
		for(var i=a.length,s=null;i>0;i--){
			if(a[i]){
				s=a[i].split(',');
				if(s[1] == link){
					console.log(s[0]);
					var scrollH=parseInt(s[0]);
					window.sessionStorage.setItem('scrollH',scrollH);
					console.log(scrollH);
//					$('html,body').animate({scrollTop:scrollH},50);
					window.scrollTo(0,scrollH);
//					$.scrollTo('html,body',scrollH);
					return;
				}
			}
		}
	}
}
/**
 *
 * @param data 需要替换的JSON数据
 */
app.regexPrice = function(data) {
    return JSON.parse((JSON.stringify(data)).replace(/(price":".*?).00/g,"$1"));
}